/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sys.donto.telas;

import java.security.Principal;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import sys.donto.financeiro.Financeiro;
import sys.donto.financeiro.FinanceiroDAO;
import sys.donto.paciente.Paciente;
import sys.donto.paciente.PacienteDAO;
import sys.donto.paciente.PacienteTableModel;
import sys.donto.servico.Servico;
import sys.donto.servico.ServicoDAO;
import sys.donto.servico.ServicoTableModel;
import sys.donto.util.ConnectionFactory;
import sys.donto.util.Util;

/**
 *
 * @author JOABB
 */
public class telaFinanceiro extends javax.swing.JDialog {
   private Financeiro financeiro;
    private List<Servico> servicos = new ArrayList<Servico>();
    /**
     * Creates new form telaRelatorios
     */
    public telaFinanceiro() {
        initComponents();
        setModal(true);
        setLocationRelativeTo(null);
        limpaCampos();
        setTitle("sysDONTO - Gerar Boleto"); //Define nome no titulo da tela
    }
    
     private void preencheTabelaDisciplinas() {
        ServicoTableModel stm = new ServicoTableModel(servicos);
        tbServiços.setModel(stm);
        calculaValorJLabel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        tfPaciente = new javax.swing.JTextField();
        btPesquisarPaciente = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbServiços = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        tfVencimento = new javax.swing.JFormattedTextField();
        jLabel10 = new javax.swing.JLabel();
        jlTotal = new javax.swing.JLabel();
        btAddServ = new javax.swing.JButton();
        tfValTotalServi = new javax.swing.JTextField();
        btExcluirServico = new javax.swing.JButton();
        btGerarBoleto = new javax.swing.JButton();
        btSair = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLFundo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel2.setLayout(null);

        tfPaciente.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfPaciente.setEnabled(false);
        jPanel2.add(tfPaciente);
        tfPaciente.setBounds(110, 130, 520, 20);

        btPesquisarPaciente.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisarPaciente.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btPesquisarPaciente.setForeground(new java.awt.Color(255, 255, 255));
        btPesquisarPaciente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btPesquisarPaciente.setToolTipText("Pesquisar Estado");
        btPesquisarPaciente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarPacienteActionPerformed(evt);
            }
        });
        jPanel2.add(btPesquisarPaciente);
        btPesquisarPaciente.setBounds(640, 130, 40, 25);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("SERVIÇO:");
        jPanel2.add(jLabel6);
        jLabel6.setBounds(40, 160, 60, 15);

        tbServiços.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tbServiços);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(110, 160, 520, 130);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel9.setText("PACIENTE:");
        jPanel2.add(jLabel9);
        jLabel9.setBounds(40, 130, 70, 15);

        tfVencimento.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        try {
            tfVencimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        tfVencimento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfVencimentoActionPerformed(evt);
            }
        });
        tfVencimento.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfVencimentoFocusLost(evt);
            }
        });
        jPanel2.add(tfVencimento);
        tfVencimento.setBounds(530, 310, 100, 20);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel10.setText("Data do Vencimento:");
        jPanel2.add(jLabel10);
        jLabel10.setBounds(390, 310, 130, 15);

        jlTotal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jlTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jlTotal.setText("VALOR TOTAL R$");
        jPanel2.add(jlTotal);
        jlTotal.setBounds(400, 350, 120, 15);

        btAddServ.setBackground(new java.awt.Color(0, 153, 153));
        btAddServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btAddServ.setToolTipText("Pesquisar Serviço");
        btAddServ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddServActionPerformed(evt);
            }
        });
        jPanel2.add(btAddServ);
        btAddServ.setBounds(640, 160, 40, 25);

        tfValTotalServi.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        tfValTotalServi.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfValTotalServi.setEnabled(false);
        jPanel2.add(tfValTotalServi);
        tfValTotalServi.setBounds(530, 340, 100, 30);

        btExcluirServico.setBackground(new java.awt.Color(0, 153, 153));
        btExcluirServico.setForeground(new java.awt.Color(0, 153, 153));
        btExcluirServico.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/trash16x16.png"))); // NOI18N
        btExcluirServico.setToolTipText("Novo Serviço");
        btExcluirServico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirServicoActionPerformed(evt);
            }
        });
        jPanel2.add(btExcluirServico);
        btExcluirServico.setBounds(640, 190, 40, 25);

        btGerarBoleto.setBackground(new java.awt.Color(0, 153, 153));
        btGerarBoleto.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btGerarBoleto.setForeground(new java.awt.Color(255, 255, 255));
        btGerarBoleto.setMnemonic('G');
        btGerarBoleto.setText("GERAR BOLETO");
        btGerarBoleto.setToolTipText("Gerar");
        btGerarBoleto.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btGerarBoleto.setFocusPainted(false);
        btGerarBoleto.setFocusable(false);
        btGerarBoleto.setRequestFocusEnabled(false);
        btGerarBoleto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGerarBoletoActionPerformed(evt);
            }
        });
        jPanel2.add(btGerarBoleto);
        btGerarBoleto.setBounds(430, 380, 120, 30);

        btSair.setBackground(new java.awt.Color(0, 153, 153));
        btSair.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btSair.setForeground(new java.awt.Color(255, 255, 255));
        btSair.setMnemonic('S');
        btSair.setText("SAIR");
        btSair.setToolTipText("Sair");
        btSair.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btSair.setFocusPainted(false);
        btSair.setFocusable(false);
        btSair.setRequestFocusEnabled(false);
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });
        jPanel2.add(btSair);
        btSair.setBounds(560, 380, 70, 30);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("FINANCEIRO DO PACIENTE");
        jLabel3.setFocusable(false);
        jPanel2.add(jLabel3);
        jLabel3.setBounds(210, 40, 360, 40);

        jLFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/telaM.jpg"))); // NOI18N
        jPanel2.add(jLFundo);
        jLFundo.setBounds(0, 0, 740, 440);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 740, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
     private void limpaCampos(){
        tfPaciente.setText("");
        tfVencimento.setText("");
        financeiro = new Financeiro();
        servicos.clear();
        preencheTabelaDisciplinas();
    }
    
    private void calculaValorJLabel() {
        double somaValServi = 0;
        for (int i = 0; i < servicos.size(); i++) {
            somaValServi += servicos.get(i).getValor();
        }
        tfValTotalServi.setText(String.valueOf(somaValServi));
    }
    
    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        dispose();
    }//GEN-LAST:event_btSairActionPerformed

    private void btPesquisarPacienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarPacienteActionPerformed
        PacienteDAO dao = new PacienteDAO();// butão de pesquisa de estado.
        List<Paciente> lista = dao.listar();
        PacienteTableModel ptm = new PacienteTableModel(lista);
        Object o = telaPesquisa.exibeTela(ptm, "paciente");
        Paciente p;
        if (o != null) {
            p = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
            financeiro.setPaciente(p);
            tfPaciente.setText(p.getNome());
        }        // TODO add your handling code here:
    }//GEN-LAST:event_btPesquisarPacienteActionPerformed

    
    
    private void tfVencimentoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfVencimentoFocusLost
        
    }//GEN-LAST:event_tfVencimentoFocusLost

    private void btGerarBoletoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGerarBoletoActionPerformed
        if (Util.chkVazio(tfPaciente.getText(),tfVencimento.getText())) {
                  
           //METODO NECESSÁRIO PARA SALVAR A DATA NO BANCO DE DADOS
            try {
                if (!tfVencimento.getText().replaceAll("/", "").isEmpty()) {
                    DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
                    java.util.Date data1;
                    data1 = new java.util.Date(fmt.parse(tfVencimento.getText()).getTime());
                    financeiro.setVencimento(data1);
                }
            } catch (ParseException ex) {
                Logger.getLogger(telaConsulta.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            financeiro.setServicos(servicos); 
            financeiro.setValTotalServicos(Double.parseDouble(tfValTotalServi.getText()));
            FinanceiroDAO dao = new FinanceiroDAO();
            dao.salvar(financeiro);// chama o metodo salvar da classe cidade.
            
            JOptionPane.showMessageDialog(rootPane, "Boleto Gerado com Sucesso!");
        }
        
        //CHAMANDO RELATORIO
        
        JasperReport pathjrxml;
        HashMap parametros = new HashMap();
        String sql = "", texto = "";

        if (!tfPaciente.getText().equals("")){
            sql += "paciente.id="+ financeiro.getPaciente().getId();
            
        Connection connection = new ConnectionFactory().getConnection();

        parametros.put("texto",sql);
        
        try{
            JDialog viewer = new JDialog(new javax.swing.JFrame(),"Visualização do Relatorio");
            viewer.setSize(1000, 600);
            viewer.setLocationRelativeTo(null);
            viewer.setModal(true);
            pathjrxml = JasperCompileManager.compileReport("src/relatorios/relatorioBoleto.jrxml");
            JasperPrint printReport = JasperFillManager.fillReport(pathjrxml, parametros, connection);
            JasperViewer jv = new JasperViewer(printReport, false);
            viewer.getContentPane().add(jv.getContentPane());
            viewer.setVisible(true);

        }catch(JRException ex){
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        }else{
            JOptionPane.showMessageDialog(rootPane, "Boleto Gerado com Sucesso!");
        }

        servicos.clear();
        
        FinanceiroDAO finDAO = new FinanceiroDAO();
        finDAO.remover(financeiro);
        
        limpaCampos();
    }//GEN-LAST:event_btGerarBoletoActionPerformed

    private void tfVencimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfVencimentoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfVencimentoActionPerformed

    private void btAddServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddServActionPerformed
        
        ServicoDAO dao = new ServicoDAO();
        List<Servico> lista = dao.listar();
        ServicoTableModel stm = new ServicoTableModel(lista);
        Object o = telaPesquisa.exibeTela(stm, "servico");
        Servico s;
            if (o != null) {
            s = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
                    servicos.add(s);
                    preencheTabelaDisciplinas();
            
            }
    }//GEN-LAST:event_btAddServActionPerformed

    private void btExcluirServicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirServicoActionPerformed
        servicos.remove(tbServiços.getSelectedRow());
        preencheTabelaDisciplinas();
    }//GEN-LAST:event_btExcluirServicoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaFinanceiro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new telaFinanceiro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAddServ;
    private javax.swing.JButton btExcluirServico;
    private javax.swing.JButton btGerarBoleto;
    private javax.swing.JButton btPesquisarPaciente;
    private javax.swing.JButton btSair;
    private javax.swing.JLabel jLFundo;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel jlTotal;
    private javax.swing.JTable tbServiços;
    private javax.swing.JTextField tfPaciente;
    private javax.swing.JTextField tfValTotalServi;
    private javax.swing.JFormattedTextField tfVencimento;
    // End of variables declaration//GEN-END:variables
}
